/*
 * Created on Feb 4, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.corpus;

import java.util.Properties;

import org.apache.log4j.Logger;

import com.hp.hpl.jena.rdf.model.Model;

/**
 * @author dfhuynh
 */
public abstract class Corpus {
	final static private Logger s_logger = Logger.getLogger(Corpus.class);

	final protected String	m_corpusURI;
	protected boolean		m_initialized = false;

	protected Model			m_model;

	protected Corpus(String corpusURI) {
		m_corpusURI = corpusURI;
	}

	synchronized public void dispose() {
		if (m_initialized) {
			if (m_model != null) {
				m_model.close();
				m_model = null;
			}

			m_initialized = false;
		}
	}

	synchronized public String getCorpusURI() {
		return m_corpusURI;
	}

	synchronized public Model getModel() {
		internalInitialize();
		return m_model;
	}

	synchronized public void add(Model model) {
		internalInitialize();
		m_model.add(model);
	}

	synchronized public void remove(Model model) {
		internalInitialize();
		m_model.remove(model);
	}

	synchronized public void removeAll() {
		internalInitialize();
		m_model.removeAll();
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.Corpus#internalInitialize()
	 */
	protected void internalInitialize() {
		if (!m_initialized) {
			try {
				createModel();
				m_initialized = true;
			} catch (Exception e) {
				s_logger.error(
					"Failed to create model for corpus " + getCorpusURI(),
					e
				);
			}
		}
	}

	abstract protected void createModel() throws Exception;

    static public Corpus createCorpus(String  corpusURI) {
        MemoryConnector connector = new MemoryConnector();
        return connector.connect(new Properties(), corpusURI);
    }

    static public Corpus createCorpus (
		String		corpusURI,
		String		connectorClassName,
		Properties	properties
	) throws Exception {
		Connector connector = (Connector)
			Class.forName(connectorClassName).newInstance();

		Corpus corpus = connector.connect(
			properties, corpusURI
		);

		return corpus;
	}
}
